var interval = 0;

$(function() {
	$('#userName').val(getUrlVars()["userName"]);
	$('#gid').val(getUrlVars()["gid"]);
	
	$('#exit-btn').click(function() { window.clearInterval(interval); logout(false); } );
	
	$('#turn-btn').click(function() { take_turn(); } );
	$('#turn-btn').attr("disabled", true);
	
	$(window).unload(function() {
		logout(true);
	});
	
	console.log("Current User: " + $('#userName').val());
	
	refresh();
	interval = setInterval("refresh()", 2000);
});

function refresh() {
  $.ajax({
    url: "/refresh",
    type: "POST",
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
      "gid": $('#gid').val(),
      "eid": $('#eid').val()
    },
    async: true,
    success: function(result) {
      if (result.error) {
        alert("Internal Server Error: See log");
        console.log(result.error);
      } else {
    	  if ($('#turn').val() == $('#userName').val() && $('#card').val() != "" && $('#target').val() != "") {
    		  $('#turn-btn').attr("disabled", false);
    		  $('#turn-info').html("Ask " + $('#target').val() + " if they have any " + get_card_string($('#card').val()) + "?");
    	  } else {
    		  $('#turn-btn').attr("disabled", true);
    		  $('#turn-info').html("<br>");
    	  }
    	  
    	  if (result.eid_dif != 0) {
    		  $('#eid').val(+$('#eid').val() + +result.eid_dif);
    		  get_game_state(); 
    	  }
      }
    },
    error: function(xhr, status, errorThrown) {
      alert("Error during refresh() type '" + status + "':\n" + errorThrown);
    }
  });
}

function get_game_state() {
	$.ajax({
		url: "/getGameState",
		type: "POST",
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		data: {
		"gid": $('#gid').val(),
		"userName": $('#userName').val()
		},
		async: true,
		success: function(result) {
			console.log("Status: get_game_state() success.");
			if (result.error) {
				alert("Internal Server Error: See log");
				console.log(result.error);
			} else if (result.winners) {
				console.log("\tGame over, someone has won.  Winners: " + result.winners);
				window.clearInterval(interval);
				alert(result.winners);
		        logout(false);
			} else {
					console.log("\tPlayer: " + result.player);
					console.log("\tOpponents: " + result.opponents);
					console.log("\tTurn: " + result.turn);
					$('#turn').val(result.turn);
					set_player_state(result.player, result.turn);
					set_opponents_state(result.opponents, result.turn);
				
				if (result.eventString) {
					console.log("\tEvent String: " + result.eventString);
					$('#game-info').val(result.eventString + "\n" + $('#game-info').val());
				}
				
				if (result.turn == $('#userName').val())
					$('#game-info').val("It is your turn...\n" + $('#game-info').val());
				else
					$('#game-info').val(result.turn + "'s turn...\n" + $('#game-info').val());
				
				if (result.deckSize) {
					console.log("\tDeck Size: " + result.deckSize);
					set_deck_picture(result.deckSize);
				}
			}
		},
		error: function(xhr, status, errorThrown) {
			alert("Error during get_game_state() type '" + status + "':\n" + errorThrown);
		}
	});
}

function set_player_state(player, turn) {
	$('#playerName').html($('#userName').val());
	$('#playerHand').html("");
	$('#playerPairs').html("");
	
	var counter = 0;
	
	for (var i in player.hand) {
		$('#playerHand').html($('#playerHand').html() + "<input type='image' class='image_input' id='" + player.hand[i] + "' src='images/" + player.hand[i] + ".png' onclick='click_card(\"" + player.hand[i] + "\")' onmouseover=''/>");
		if (counter >= 4) {
			$('#playerHand').html($('#playerHand').html() + "<br>");
			counter = 0;
		} else {
			counter++;
		}
	}
	
	counter = 0;
	
	for (var j in player.pairs) {
		$('#playerPairs').html($('#playerPairs').html() + "<img src='images/" + player.pairs[j] + ".png'/><img class='pairs' src='images/card_edge_right.png'/>");
		if (counter >= 4) {
			$('#playerPairs').html($('#playerPairs').html() + "<br>");
			counter = 0;
		} else {
			counter++;
		}
	}
}

function set_opponents_state(opponents, turn) {
	$('#opponents').html("");
	var html_str = "</br>";
	
	for (var x in opponents) {
		
		html_str += "<table class='opponent_table' id='" + x + "-opp' onclick='click_target(\"" + opponents[x].userName + "\")'><tr><td>Name:</td><td>" + opponents[x].userName;
		
		html_str += "</td></tr><tr><td>Hand:</td><td>";
		
		for (var y = 0; y < opponents[x].hand; y++) {
			if (y == 0)
				html_str += "<img src='images/card_vertical.png'/>";
			else
				html_str += "<img src='images/card_edge_right.png'/>";
		}
		
		html_str += "</td></tr><tr><td>Pairs:</td><td>";
		
		for (var z in opponents[x].pairs) {
			html_str += "<img src='images/" + opponents[x].pairs[z] + ".png'/><img class='pairs' src='images/card_edge_right.png'/>";
		}
		
		html_str += "</td></tr></table></button></br>";

		$('#opponents').html(html_str);
	}
}

function take_turn() {
	$.ajax({
		url: "/takeTurn",
		type: "POST",
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		data: {
			"gid": $('#gid').val(),
			"card": $('#card').val(),
			"target": $('#target').val(),
			"userName": $('#userName').val()
		},
		async: true,
		success: function(result) {
			if (result.error) {
				alert("Internal Server Error: See log");
				console.log(result.error);
			} else {
				console.log("Status: take_turn() success.");
				$('#card').val("");
				$('#target').val("");
				refresh();
			}
		},
		error: function(xhr, status, errorThrown) {
			alert("Error during take_turn() type '" + status + "':\n" + errorThrown);
		}
	});
}

function click_card(card) {
	$('#card').val(card);
	refresh();
}

function click_target(target) {
	$('#target').val(target);
	refresh();
}

function get_card_string(card) {	
	if (card != "") {
		switch(card.charAt(0)) {
			case '1':
				return "ones";
			case '2':
				return "twos";
			case '3':
				return "threes";
			case '4':
				return "fours";
			case '5':
				return "fives";
			case '6':
				return "sixes";
			case '7':
				return "sevens";
			case '8':
				return "eights";
			case '9':
				return "nines";
			case 'T':
				return "tens";
			case 'J':
				return "Jacks";
			case 'Q':
				return "Queens";
			case 'K':
				return "Kings";
			case 'A':
				return "Aces";
		}
	}
	
	return "";
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function set_deck_picture(deck_size)
{
	var html_str = "";
	var full_card = "<img src='images/card_vertical.png'/>";
	var edge_card = "<img src='images/card_edge_right.png'/>";
	var col_counter = 29;
	
	while (deck_size > 0) {
		html_str += full_card;
		deck_size--;
		while (deck_size > 0 && col_counter > 0) {
			html_str += edge_card;
			col_counter --;
			deck_size--;
		}
		col_counter = 19;
		html_str += "</br>";
	}
	
	$('#deck-picture').html(html_str);
}

function logout(unload) {
	$.ajax({
		url: "/leaveGroup",
		type: "POST",
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		data: {
			"userName": $('#userName').val(),
			"gid": $('#gid').val()
		},
		async: false,
		success: function(result) {
			console.log("Status: logout() success.");
			if (!unload) {
				console.log("Returning to index.");
				var url = String(window.location).substring(0, String(window.location).indexOf("board.html") - 1);
				window.open(url, "_top");
			}
		},
		error: function(xhr, status, errorThrown) {
			alert("Error during logout() type " + status + ":\n" + errorThrown);
		}
	});
}
